<template>
  <div>
    <el-form label-position="right" label-width="150px" :model="writerForm" :rules="rules">
      <el-form-item label="数据库源：" prop="datasourceId">
        <el-select v-model="writerForm.datasourceId" filterable clearable style="width: 30%" @change="wDsChange">
          <el-option
            v-for="item in wDsList" :key="item.datasourceId" :label="item.datasourceGroup + '_' + item.datasourceName + '_' + item.datasourceType"
            :value="item.datasourceId" />
        </el-select>
      </el-form-item>
      <el-form-item v-show="datasourceType==='postgresql' || datasourceType==='oracle'" label="Schema：" prop="tableSchema">
        <el-select v-model="writerForm.tableSchema" filterable clearable style="width: 30%" @change="schemaChange">
          <el-option v-for="item in schemaList" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="数据库表名：" prop="tableName">
        <el-select
          v-model="writerForm.tableName" allow-create default-first-option filterable clearable :disabled="writerForm.ifCreateTable" style="width: 30%"
          @change="wTbChange">
          <el-option v-for="item in wTbList" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <div style="margin: 5px 0;" />
      <el-form-item label="字段：">
        <el-checkbox v-model="writerForm.checkAll" :indeterminate="writerForm.isIndeterminate" @change="wHandleCheckAllChange">全选
        </el-checkbox>
        <div style="margin: 15px 0;" />
        <el-checkbox-group v-model="writerForm.columns" @change="wHandleCheckedChange">
          <el-checkbox v-for="c in fromColumnList" :key="c" :label="c">{{ c }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="前置sql语句：">
        <el-input v-model="writerForm.preSql" placeholder="前置sql在insert之前执行【多个sql语句, 用英文分号分隔】" type="textarea" :rows="6" style="width: 60%" />
        <!-- <el-button v-if="this.showInitSql" type="primary" @click="getPreSql(writerForm.tableName)">内置sql</el-button> -->
      </el-form-item>
      <el-form-item label="后置sql语句：">
        <el-input v-model="writerForm.postSql" placeholder="后置sql在insert之后执行【多个sql语句, 用英文分号分隔】" type="textarea" :rows="8" style="width: 60%" />
        <!-- <el-button v-if="writerForm.tableName != ''" type="primary" @click="getPostSql(writerForm.tableName)">内置 后置sql</el-button> -->
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { selectTables, selectSchema, selectColumns } from '@data/api/data/datacollection'
import { search as datasourceList } from '@data/api/data/datasource'
import { useDataStore } from '@/store/modules/data'
// import Bus from '../busWriter'

export default {
  name: 'RDBMSWriter',
  data() {
    return {
      wDsList: [],
      schemaList: [],
      fromTableName: '',
      fromColumnList: [],
      wTbList: [],
      datasourceType: '',
      createTableName: '',
      showInitSql: false,
      writerForm: {
        datasourceId: undefined,
        tableName: '',
        columns: [],
        checkAll: false,
        isIndeterminate: true,
        preSql: '',
        postSql: '',
        ifCreateTable: false,
        tableSchema: '',
        initSql: 1
      },
      readerForm: this.getReaderData(),
      rules: {
        datasourceId: [{ required: true, message: '请选择数据源', trigger: 'change' }],
        tableName: [{ required: true, message: '请选择数据库表名', trigger: 'change' }],
        tableSchema: [{ required: true, message: '数据库表名必填', trigger: 'change' }]
      }
    }
  },
  watch: {
    'writerForm.datasourceId': function (oldVal, newVal) {
      if (this.datasourceType === 'postgresql' || this.datasourceType === 'oracle' || this.datasourceType === 'sqlserver') {
        this.getSchema()
      } else {
        this.getTables('rdbmsWriter')
      }
    }
  },
  created() {
    this.getJdbcDs()
  },
  methods: {
    // 获取可用数据源
    getJdbcDs() {
      this.loading = true
      datasourceList().then(response => {
        const { list } = response.data
        this.wDsList = list
        this.loading = false
      })
    },
    // 获取表名
    getTables(type) {
      if (type === 'rdbmsWriter') {
        let obj = {}
        if (this.datasourceType === 'postgresql' || this.datasourceType === 'oracle' || this.datasourceType === 'sqlserver') {
          obj = {
            datasourceId: this.writerForm.datasourceId,
            tableSchema: this.writerForm.tableSchema
          }
        } else {
          obj = {
            datasourceId: this.writerForm.datasourceId
          }
        }
        // 组装
        selectTables(obj).then(response => {
          this.wTbList = response.data
        })
      }
    },
    getSchema() {
      const obj = {
        datasourceId: this.writerForm.datasourceId
      }
      selectSchema(obj).then(response => {
        this.schemaList = response.data
      })
    },
    // schema 切换
    schemaChange(e) {
      this.writerForm.tableSchema = e
      // 获取可用表
      this.getTables('rdbmsWriter')
    },
    wDsChange(e) {
      // 清空
      // this.fromTableName = ''
      this.writerForm.tableName = ''
      this.writerForm.tableSchema = ''
      this.fromColumnList = []
      this.writerForm.preSql = ''
      this.showInitSql = true //false

      this.writerForm.datasourceId = e
      this.wDsList.find((item) => {
        if (item.datasourceId === e) {
          this.datasourceType = item.datasourceType
          if(this.datasourceType === 'clickhouse') {
            this.showInitSql = true
            this.writerForm.initSql = 0
          }
        }
      })
      const dataStore = useDataStore()
      dataStore.setDataSourceId(e)
      // Bus.dataSourceId = e
      this.$emit('selectDataSource', this.datasourceType)
    },
    // 获取表字段
    getColumns() {
      const obj = {
        datasourceId: this.writerForm.datasourceId,
        tableName: this.writerForm.tableName
      }
      //1、获取表字段
      selectColumns(obj).then(response => {
        this.fromColumnList = response.data
        this.writerForm.columns = response.data
        this.writerForm.checkAll = true
        this.writerForm.isIndeterminate = false
      })
    },
    // 表切换
    wTbChange(t) {
      this.writerForm.preSql = ''
      this.writerForm.postSql = ''
      this.writerForm.tableName = t
      this.fromColumnList = []
      this.writerForm.columns = []

      this.getColumns('writer')

      // by zwb ：直接用 reader页面的字段
      // this.writerForm.columns = this.fromColumnList
    },
    wHandleCheckAllChange(val) {
      this.writerForm.columns = val ? this.fromColumnList : []
      this.writerForm.isIndeterminate = false
    },
    wHandleCheckedChange(value) {
      const checkedCount = value.length
      this.writerForm.checkAll = checkedCount === this.fromColumnList.length
      this.writerForm.isIndeterminate = checkedCount > 0 && checkedCount < this.fromColumnList.length
    },
    getData() {
      // const dataStore = useDataStore()
      // if (dataStore.getDataSourceId) {
      //   this.writerForm.datasourceId = dataStore.getDataSourceId
      // }
      return this.writerForm
    },
    // by zwb
    sendColumns(fromColumnList) {
      this.fromColumnList = fromColumnList
    },
    getReaderData() {
      return this.$parent.getReaderData()
    },
    getTableName() {
      // return this.fromTableName
      return this.writerForm.tableName
    },
    resetForm() {
      this.writerForm = {
        datasourceId: undefined,
        tableName: '',
        columns: [],
        checkAll: false,
        isIndeterminate: true,
        preSql: '',
        postSql: '',
        ifCreateTable: false,
        tableSchema: ''
      }
    },
    // getPreSql(tableName) {
    //   this.writerForm.preSql = 'truncate table ' + tableName
    //   if(this.datasourceType === 'clickhouse') {
    //     this.writerForm.preSql = 'truncate table ' + tableName + ' on cluster ck_cluster'
    //   }
    //   this.writerForm.initSql = 1
    // }
  }
}
</script>
